<?php
class UserCtrl extends ControllerBase {
    public function OnInit(){
        $this->IsUserAuthenticationRequired(true);
        parent::OnInit();
    }

    public function OnLoad(){
        $this->SetAuthentication();
        parent::OnLoad();
    }

    public function Index() {
        parent::Title($this->Resource("TXT_PAGE_TITLE_MY_DETAILS"));
    }

    public function Login() {
        parent::Title($this->Resource("TXT_PAGE_TITLE_LOGIN"));

        if($this->User()->IsLoggedIn()){
            $this->Info($this->Resource("TXT_INFO_LOGGED_IN_ALREADY"));
        }
        else if($this->IsPostBack()){
            $this->User()->ValidatePostToken();
            $username = self::GetValueFromPost("username");
            $password = self::GetValueFromPost("password");
            if(count($this->Error()) == 0){
                $this->User()->Login($username, $password);
            }
        }
    }

    public function Logout() {
        parent::Title($this->Resource("TXT_PAGE_TITLE_LOGOUT"));
        $this->User()->Logout();
    }

    private function GetValueFromPost($key) {
        if(!isset($_POST[$key]) || empty($_POST[$key])){
            $this->Error($this->Resource("TXT_ERROR_FIELD_IS_MANDATORY", $key));
        }
        else{
            return $_POST[$key];
        }
        return null;
    }
}
